//
//  MajorViewController.swift
//  miaoyin
//
//  Created by David on 2017/2/23.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

class MajorViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }
    
    var delegate: SchoolSelectDelegate?
    
    var schoolData: Any?
    
    convenience init(schoolData: Any){
        self.init()
        self.schoolData = schoolData
    }
//    
//    var regData: String?
//    
//    convenience init(schoolData: Any, regData: String){
//        self.init()
//        self.schoolData = schoolData
//        self.regData = regData
//    }
    
    var tableView: UITableView!
    var searchBar: UITextField!
    
    var majorData: NSArray?
    var searchResult: NSArray?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "所在专业"
        navigationController?.setNavigationBarHidden(true, animated: false)
        
        let navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
        navBar.barTintColor = themeColor2
        navBar.barStyle = .black
        navBar.tintColor = UIColor.white
        
        
        let navItem = UINavigationItem(title: "所在专业")
        navItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "navbar_back"), style: .plain, target: self, action: #selector(MajorViewController.goBack))
        navBar.pushItem(navItem, animated: true)
        
        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height))
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView(frame: CGRect.zero)
        tableView.keyboardDismissMode = .onDrag
        view.addSubview(tableView)
        
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 44))
        headerView.backgroundColor = UIColor.groupTableViewBackground
        
//        searchBar = UITextField(frame: CGRect(x: 16, y: 8, width: view.bounds.width - 32, height: 28))
//        searchBar.font = UIFont.systemFont(ofSize: 14)
//        searchBar.placeholder = "搜索学校名称"
//        searchBar.backgroundColor = UIColor.white
//        searchBar.layer.cornerRadius = 4
//        searchBar.returnKeyType = .search
//        searchBar.enablesReturnKeyAutomatically = true
//        searchBar.clearButtonMode = .always
//        headerView.addSubview(searchBar)
//        searchBar.addTarget(self, action: #selector(MajorViewController.searchBarFinish), for: .editingDidEndOnExit)
//        searchBar.addTarget(self, action: #selector(SchoolViewController.searchBarEnd), for: .editingDidEnd)
        
        tableView.tableHeaderView = headerView
        
        view.addSubview(navBar)
        
        loadMajor()
        
    }
    
    func loadMajor(){
        if schoolData != nil{
            let schoolInfo = schoolData as? NSDictionary
            let schoolID = schoolInfo?.object(forKey: "id") as? String
            if schoolID != nil{
                var resq = URLRequest(url: URL(string: "\(Fatcat.SERVER_DOMAIN_NAME)/index.php?m=admin&c=user&a=schoolmajor")!)
                resq.httpMethod = "POST"
                resq.httpBody = "uid=\(schoolID!)".data(using: .utf8)
                
                URLSession.shared.dataTask(with: resq, completionHandler: { (data:Data?, resp:URLResponse?, err:Error?) in
                    do{
                        if err != nil{
                            throw err!
                        }
                        
                        let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                        self.majorData = jsonObj?.object(forKey: "data") as? NSArray
                        
                        DispatchQueue.main.async {
                            self.tableView.reloadData()
                        }
                        
                        
                    }catch let ex{
                        print(ex)
                    }
                }).resume()
                
            }
        }
    }
    
    func searchBarFinish(){
        if searchBar.text != "" {
            
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return majorData?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "item")
        
        let major = majorData?.object(at: indexPath.row) as? NSDictionary
        cell.textLabel?.text = major?.object(forKey: "name") as? String
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if majorData != nil{
            if FCUserReg.shared.isRegisterStarted{
                let major = majorData?.object(at: indexPath.row) as? NSDictionary
                let majorID = major?.object(forKey: "id") as? String
                if majorID != nil{
                    FCUserReg.shared.schoolId = majorID
                }
                
                navigationController?.pushViewController(YearPickerViewController(), animated: true)
            }else{
                _ = navigationController?.popViewController(animated: false)
                delegate?.schoolView?(data: majorData!.object(at: indexPath.row))
            }
            
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func goBack(){
        _ = navigationController?.popViewController(animated: true)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
